package com.lancoo.lancooimageloader.glide;

import android.content.Context;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestOptions;
import com.lancoo.lancooimageloader.LancooCancelableCallback;
import com.lancoo.lancooimageloader.LancooImageCallback;
import com.lancoo.lancooimageloader.LancooImageManager;
import com.lancoo.lancooimageloader.LancooImageOptions;
import com.lancoo.lancooimageloader.OptionConverter;

/**
 * Author: Andecy
 * Time: 2017/5/24
 * Email: andecy@foxmail.com
 * Description: TODO
 */

public class GlideLoaderImpl implements LancooImageManager {
    private Context mContext;

    public GlideLoaderImpl(Context mContext) {
        this.mContext = mContext;
    }

    @Override
    public void load(ImageView view, String url) {
        Glide.with(view.getContext()).load(url).into(view);
    }

    @Override
    public void load(ImageView view, String url, LancooImageOptions options) {
        load(view, url, options, null);
    }

    @Override
    public void load(ImageView view, String url, LancooImageCallback callback) {
        //  Glide.with(mContext).load(url).listener(new GlideImageCallback<>(callback)).into(view);
        load(view, url, null, callback);
    }

    @Override
    public void load(ImageView view, String url, LancooImageOptions options, LancooImageCallback callback) {
        if (options != null) {
            OptionConverter converter = options.getConverter();
            if (converter.getImageOptions() instanceof RequestOptions) {
                if (!options.isIgnoreGif()) {//加载gif
                  //  Log.e("laod---->", "1gif");
                    Glide.with(mContext).asGif().load(url)
                            .apply((RequestOptions) converter.getImageOptions()).listener(new GlideImageCallback<GifDrawable>(callback)).into(view);
                } else {
                   // Log.e("laod---->", "2Nogif");
                    Glide.with(mContext)
                            .load(url).apply((RequestOptions) converter.getImageOptions()).listener(new GlideImageCallback<>(callback)).into(view);
                }
            }
        } else {
            Glide.with(mContext).load(url)
                    .listener(new GlideImageCallback<>(callback)).into(view);
        }
    }

    @Override
    public LancooCancelableCallback loadDrawable(String url, LancooImageOptions options, LancooImageCallback callback) {
        RequestManager requestManager = Glide.with(mContext);
        requestManager.load(url).
                listener(new GlideImageCallback<>(callback));
        return new GlideCancelableCallback(requestManager);

    }

    @Override
    public void clearMemCache() {
        Glide.get(mContext).clearMemory();
    }

    @Override
    public void clearCacheFiles() {
        Glide.get(mContext).clearDiskCache();
    }
}
